<template>
    <div>
        <div class="cardContainer">
            <div class="row1">
                <div class="plan card">
                    <el-card shadow="always"> 
                        <div class="title">
                            套餐类型
                        </div>
                        <div class="content">
                            {{tenantInfo.plan? tenantInfo.plan: "免费套餐"}} 
                        </div>
                        <div class="note">
                            更改套餐，次月生效
                        </div>
                    </el-card>
                    <div class="changePlan" @click="changePlan">
                        <el-tag>更改套餐</el-tag>
                    </div>
                </div>
                <div class="balance card">
                    <el-card shadow="always"> 
                        <div class="title">
                            余额
                        </div>
                        <div class="content">
                            ¥{{ tenantInfo.balance.toFixed(2)}} 
                        </div>
                        <div class="note">
                            优先使用赠送金额
                        </div>
                    </el-card>
                    <div class="addCharge" @click="addCharge">
                        <el-tag type="success">充值</el-tag>
                    </div>
                </div>
                <div class="gift card">
                    <el-card shadow="always">
                        <div class="title">
                            赠送金额
                        </div>
                        <div class="content">
                            ¥{{ tenantInfo.gift.toFixed(2)}} 
                        </div>
                        <div class="note">
                            管理员不定时赠送
                        </div>
                    </el-card>
                </div>
            </div>
            <div class="row2">
                <div class="rappoints card">
                    <el-card shadow="always"> 
                        <div class="title">
                            RPA点数余额
                        </div>
                        <div class="content">
                            {{tenantInfo.rpapoints}}点
                        </div>
                        <div class="note">
                            可通过余额或赠送金额兑换
                        </div>
                    </el-card>
                    <div class="redeem" @click="redeemAction">
                        <el-tag type="success">兑换</el-tag>
                    </div>
                </div>
                <div class="envlimit card">
                    <el-card shadow="always">
                        <div class="title">
                            环境数
                        </div>
                        <div class="content">
                            <el-progress :text-inside="true" :stroke-width="20" :percentage="getEnvLimitPercent()" />
                        </div>
                        <div class="note">
                            {{tenantInfo.usedEnv? tenantInfo.usedEnv:0}}/{{tenantInfo.envLimit}}
                        </div>
                    </el-card>
                </div>
                <div class="userlimit card">
                    <el-card shadow="always">
                        <div class="title">
                            用户数
                        </div>
                        <div class="content">
                            <el-progress :text-inside="true" :stroke-width="20" :percentage="getUserLimitPercent()" />
                        </div>
                        <div class="note">
                            {{tenantInfo.usedUser?tenantInfo.usedUser:0}}/{{tenantInfo.userLimit}}
                        </div>
                    </el-card>
                </div>
            </div>
        </div>
        <div class="orderList">
            <div class="title">订单详情</div>
            <el-table 
                :data="tableData" 
                max-height="500"
                stripe
                style="width: 100%"
                :cell-style="{textAlign:'center'}"
                :header-cell-style="{textAlign:'center'}"
            >
                <el-table-column prop="type" label="类型" width="180" />
                <el-table-column prop="amount" label="金额" width="180" />
                <el-table-column prop="note" label="描述" />
                <el-table-column prop="createTime" label="日期" width="155" :formatter="formatTime"/>
            </el-table>

            <div class="pagination">
                <el-pagination
                    v-model:current-page="currentPage"
                    v-model:page-size="pageSize"
                    :page-sizes="[10, 20, 30, 50, 100, 150, 200, 250, 300]"
                    :small="false"
                    :disabled="false"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    total-text="总共"
                    style="justify-content:end"
                />
            </div>
        </div>
        <ChangePlanDialog v-if="isShowChangePlanDialog" v-model:is-show="isShowChangePlanDialog" :plan="tenantInfo.plan" :handleUpdated="handleUpdatedPlan"></ChangePlanDialog>
        <RedeemDialog v-if="isShowRedeemDialog" v-model:is-show="isShowRedeemDialog" :handleUpdated="handleUpdatedPlan"></RedeemDialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted,reactive, computed, defineProps, defineEmits, watch} from 'vue'
import {useRouter, useRoute} from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus'
import TenantApi from '../../apis/tenant'
import ChangePlanDialog from './ChangePlanDialog.vue';
import RedeemDialog from './Redeem.vue';
import {formatTime} from '../../utils/TimeUtils'
import { storeToRefs } from 'pinia'
import {useUserStore} from '../../stores/user'
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore);

const router = useRouter();
const route = useRoute();

const tableData = ref([]);
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(200)
const isShowChangePlanDialog = ref(false);
const isShowRedeemDialog = ref(false);
const tenantInfo = ref({
    plan: "",
    balance: 0,
    gift: 0,
    rpapoints: 0,
    envLimit: 0,
    userLimit: 0,
    usedEnv: 0,
    usedUser: 0
});

onMounted(()=>{
    loadData();
});

const loadData = () =>{
    TenantApi.fetchTenantInfo().then(ret=>{
        if(ret.code == 0){
            tenantInfo.value = ret.data;
            console.log('[Billings]', tenantInfo.value);
        }else{
            ElMessage({
                type:"error",
                message: "获取租户信息失败",
            })
        }
    }).catch(err=>{
        ElMessage({
            type:"error",
            message: err
        })
    });
    TenantApi.fetchTenantOrder(currentPage.value-1, pageSize.value).then(ret=>{
        console.log('[Billings]', ret);
        tableData.value = ret.data.list;
        total.value = ret.data.totalCount;
        currentPage.value = ret.data.page + 1;
        pageSize.value = ret.data.pageSize;
    }).catch(err=>{
        console.log('[Billings]', err);
        ElMessage({
            type:"error",
            message: "获取订单信息失败",
        })
    })
}

const changePlan = () =>{
    isShowChangePlanDialog.value = true;
}

const addCharge = () => {
    ElMessage({
        type:"warning",
        message: "请联系管理员充值, 微信号Elliottxu"
    })
}

const redeemAction = ()=>{
    isShowRedeemDialog.value = true;
}

const handleUpdatedPlan = ()=>{
    loadData();
}

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  loadData();
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  loadData();
}

const getEnvLimitPercent = ()=>{
    if(tenantInfo.value.envLimit == 0){
        return 0;
    }
    return (tenantInfo.value.usedEnv/tenantInfo.value.envLimit)*100;
}

const getUserLimitPercent = ()=>{
    console.log("getUserLimitPercent", tenantInfo.value.usedUser, tenantInfo.value.userLimit);
    if(tenantInfo.value.userLimit == 0){
        return 0;
    }
    return (tenantInfo.value.usedUser/tenantInfo.value.userLimit)*100;
}
</script>

<style scoped>
.cardContainer {
    display: flex;
    flex-direction: column;
}
.cardContainer .row1, .cardContainer .row2{
    display: flex;
    flex-direction: row;
    justify-content: start;
}
.row2 {
    margin-top: 20px;
}
.row1 .card, .row2 .card{
    width: 30%;
    position: relative;
}
.balance, .gift, .envlimit, .userlimit {
    margin-left: 20px;
}

.orderList{
    margin-top: 20px;
}
.orderList .title{
    margin-bottom: 10px;
}
.card .title {
    font-size: 13px;
    text-transform: uppercase;
    color: #8898aa;
    font-weight: 600;
}
.card .content {
    font-size: 20px;
    color: #525252;
    font-weight: 700;
    margin-top:6px;
}
.card .note {
    font-size: 14px;
    color: #515a6e;
    margin-top: 6px;
}

.changePlan, .addCharge, .redeem {
    position:absolute;
    right: 5px;
    top: 5px;
    cursor: pointer;
}
.pagination {
    margin-top:10px;
}

</style>
